package com.moyun.controller.org;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moyun.common.annotation.OperLog;
import com.moyun.common.aspect.BusinessType;
import com.moyun.model.common.PageDTO;
import com.moyun.model.common.PageParam;
import com.moyun.model.common.PageResult;
import com.moyun.model.common.R;
import com.moyun.model.po.org.SysOrgRoleEntity;
import com.moyun.model.po.org.SysOrgRoletreeEntity;
import com.moyun.service.org.SysOrgRoleService;
import com.moyun.service.org.SysOrgRoletreeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yangboxuan
 * @since 2021-06-01
 */
@Api(tags = "角色树")
@RestController
@RequestMapping("/org/sys-org-roletree")
public class SysOrgRoletreeController {
    @Autowired
    private SysOrgRoletreeService sysOrgRoletreeEntityService;
    @Autowired
    private SysOrgRoleService sysOrgRoleService;

    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 带条件的分页查询
     * @Date 2021/6/1 11:29
     * @Param [params]
     **/
    @ApiOperation("带条件的分页查询")
    @PostMapping({"/select-condition", "select-tree"})
    @OperLog(operModul = "角色树模块", operType = BusinessType.QUERY, operDesc = "分页查询")
    public R selectCondition(@RequestBody PageParam<SysOrgRoletreeEntity> params, HttpServletRequest request) {
        PageDTO pageParams = params.getPageParams();
        Page<SysOrgRoletreeEntity> page = new Page<>(pageParams.getCurrent(), pageParams.getSize());


        SysOrgRoletreeEntity sysOrgRoletreeEntity = params.getEntityParams();
        QueryWrapper<SysOrgRoletreeEntity> queryWrapper = new QueryWrapper<>();
        if (sysOrgRoletreeEntity != null) {
            queryWrapper.eq(sysOrgRoletreeEntity.getTreeId() != null, "tree_id", sysOrgRoletreeEntity.getTreeId());
        }
        this.sysOrgRoletreeEntityService.page(page, queryWrapper);


        String requestURI = request.getRequestURI();
        if ("/org/sys-org-roletree/select-tree".equals(requestURI)) {
            // 获取sql中查询出来的对象集合
            List<SysOrgRoletreeEntity> records = page.getRecords();
            // 构建node列表
            List<TreeNode<String>> nodeList = records.stream().map(entity -> {
                // 树节点扩展属性(也叫扩展树结点的属性) 树节点本身属性: id parentId(父节点id) name(名称) weight(权重)
                Map<String, Object> map = new HashMap<>();
                map.put("treeId", entity.getTreeId());
                map.put("id", entity.getId());
//            map.put("gmt_modifier", LocalDateTime.now());
                TreeNode<String> treeNode = new TreeNode<String>()
                        .setId(entity.getLevelId())
                        .setParentId(entity.getParentLevelId())
                        .setName(entity.getLevelName())
                        .setWeight(entity.getSortNum())
                        .setExtra(map);
                return treeNode;
            }).collect(Collectors.toList());
            //配置
            TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
            // 自定义属性名 都要默认值的 TreeNode的原有属性名是: id parentId(父节点id) name(名称) weight(权重)
            // 这里改为数据库中存储的字段--实体类属性名
            treeNodeConfig.setIdKey("levelId");
            treeNodeConfig.setParentIdKey("parentLevelId");
            treeNodeConfig.setWeightKey("sortNum");
            treeNodeConfig.setNameKey("levelName");
            // 最大递归深度
            treeNodeConfig.setDeep(3);
            //转换器
            List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "000", treeNodeConfig,
                    (treeNode, tree) -> {
                        tree.setId(treeNode.getId());
                        tree.setParentId(treeNode.getParentId());
                        tree.setWeight(treeNode.getWeight());
                        tree.setName(treeNode.getName());
                        // 扩展属性 ...
                        tree.putExtra("treeId", treeNode.getExtra().getOrDefault("treeId", null));
                        tree.putExtra("id", treeNode.getExtra().getOrDefault("id", null));
                    });
            return R.ok(new PageResult(page.getTotal(), treeNodes));
        } else {
            return R.ok(new PageResult<SysOrgRoletreeEntity>(page.getTotal(), page.getRecords()));
        }
    }

    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 带条件的分页查询
     * @Date 2021/6/1 11:29
     * @Param [params]
     **/
    @ApiOperation("系统组织角色树查询")
    @PostMapping({"select-tree2"})
    @OperLog(operModul = "角色树模块", operType = BusinessType.QUERY, operDesc = "分页查询")
    public R selectCondition2(@RequestBody PageParam<SysOrgRoletreeEntity> params, HttpServletRequest request) {
        PageDTO pageParams = params.getPageParams();
        Page<SysOrgRoletreeEntity> page = new Page<>(pageParams.getCurrent(), pageParams.getSize());


        SysOrgRoletreeEntity sysOrgRoletreeEntity = params.getEntityParams();
        QueryWrapper<SysOrgRoletreeEntity> queryWrapper = new QueryWrapper<>();
        if (sysOrgRoletreeEntity != null) {
            queryWrapper.eq(sysOrgRoletreeEntity.getTreeId() != null, "tree_id", sysOrgRoletreeEntity.getTreeId());
        }
        this.sysOrgRoletreeEntityService.page(page, queryWrapper);
        // 系统组织角色的集合
        //        List<SysOrgRoleEntity> sysOrgRoleEntityList = this.sysOrgRoleService.list(new QueryWrapper<SysOrgRoleEntity>().eq("is_delete", "0"));
        List<SysOrgRoleEntity> sysOrgRoleEntityList = this.sysOrgRoleService.list();

        String requestURI = request.getRequestURI();
        if ("/org/sys-org-roletree/select-tree2".equals(requestURI)) {
            // 获取sql中查询出来的对象集合
            List<SysOrgRoletreeEntity> records = page.getRecords();
            // 构建node列表
            List<TreeNode<String>> nodeList = records.stream().map(entity -> {
                // 树节点扩展属性(也叫扩展树结点的属性) 树节点本身属性: id parentId(父节点id) name(名称) weight(权重)
                Map<String, Object> map = new HashMap<>();
                map.put("treeId", entity.getTreeId());
                map.put("id", entity.getId());
                List<SysOrgRoleEntity> collect = sysOrgRoleEntityList.stream().filter((sysOrgRoleEntity) -> sysOrgRoleEntity.getLevelId().equals(entity.getLevelId())).collect(Collectors.toList());
                map.put("children", collect);
//            map.put("gmt_modifier", LocalDateTime.now());
                TreeNode<String> treeNode = new TreeNode<String>()
                        .setId(entity.getLevelId())
                        .setParentId(entity.getParentLevelId())
                        .setName(entity.getLevelName())
                        .setWeight(entity.getSortNum())
                        .setExtra(map);
                return treeNode;
            }).collect(Collectors.toList());
            //配置
            TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
            // 自定义属性名 都要默认值的 TreeNode的原有属性名是: id parentId(父节点id) name(名称) weight(权重)
            // 这里改为数据库中存储的字段--实体类属性名
            treeNodeConfig.setIdKey("levelId");
            treeNodeConfig.setParentIdKey("parentLevelId");
            treeNodeConfig.setWeightKey("sortNum");
            treeNodeConfig.setNameKey("levelName");
            // 最大递归深度
            treeNodeConfig.setDeep(3);
            //转换器
            List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "000", treeNodeConfig,
                    (treeNode, tree) -> {
                        tree.setId(treeNode.getId());
                        tree.setParentId(treeNode.getParentId());
                        tree.setWeight(treeNode.getWeight());
                        tree.setName(treeNode.getName());
                        // 扩展属性 ...
                        tree.putExtra("treeId", treeNode.getExtra().getOrDefault("treeId", null));
                        tree.putExtra("id", treeNode.getExtra().getOrDefault("id", null));
                        tree.putExtra("children", treeNode.getExtra().getOrDefault("children", null));
                    });
            return R.ok((new PageResult(page.getTotal(), treeNodes)));
        } else {
            return R.ok(new PageResult<SysOrgRoletreeEntity>(page.getTotal(), page.getRecords()));
        }
    }


}

